#include<stdio.h>
#include<unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include<string.h>
#include<errno.h>
char arr[512];
#define SPLID " "
#define NUM 32
char*argv[NUM];
int errorcode=0;
char* name()
{
    char* na=getenv("USER");
   if(na==NULL)
     return NULL;
     return na;
}
char*hostname()
{

  char* ho=getenv("HOSTNAME");
  if(ho==NULL)
    return NULL;
    return ho;



}
char*pwd()
{
char* pw=getenv("PWD");
if(pw==NULL)
   return NULL;

  char*p=pw+strlen(pw)-1;
  while((*p)!='/')p--;

   return p;



}
void commondline()
{    printf("[%s@%s %s]$",name(),hostname(),strlen(pwd())==1 ? "/":pwd()+1);

}
char*gethome()
{
char*home=getenv("HOME");
if(home==NULL)return NULL;
   return home;


}
void getcommondstr(int size)
{
    fgets(arr,size,stdin);
    arr[strlen(arr)-1]='\0';
}
void splitcommand()
{
 argv[0]=strtok(arr,SPLID);
 int index=1;
 while((argv[index++]=strtok(NULL,SPLID)));
}
void  finishcommand()
{
 int id=fork();
 if(id==0)
 {
  execvp(argv[0],argv);
  exit(errno);
 }
 int status=0;
 int rf=waitpid(id,&status,0);
 if(rf>0)
 {
 // printf("exit sussess,exitcode:%d",WEXITSTATUS(status));
 errorcode=WEXITSTATUS(status);
 if(errorcode!=0)printf("%s:%s:%d\n",argv[0],strerror(errorcode),errorcode);
 }
 
}
void cd()
{
 char* path=argv[1];
 if(path==NULL)path=gethome();
  chdir(path);
  
  char cwd[1024];
  char temp[1024];
  getcwd(temp,sizeof(temp));
  snprintf(cwd,sizeof(cwd),"PWD=%s",temp);
  putenv(cwd);
}
int Built_incommands()
{ int yes=0;
 char* built=argv[0];
 if(strcmp(built,"cd")==0)
 {
  yes=1;
  cd();
 }
 else if(strcmp(built,"echo")==0&&strcmp(argv[1],"$?")==0)
 {
 yes=1;
printf("%d\n",errorcode);
errorcode=0;
 }

return yes;

}
int main()
{ int quit=0;
  while(!quit)
  {
    commondline();
    getcommondstr(sizeof(arr));
    splitcommand();
   int res= Built_incommands();
   if(res)continue;
   finishcommand();

}}
